package com.cskaoyan.service.wxcart;

import com.cskaoyan.bean.*;
import com.cskaoyan.controller.TestController;
import com.cskaoyan.mapper.*;
import com.cskaoyan.model.bo.wxcart.CartAddBo;
import com.cskaoyan.model.bo.wxcart.CartCheckedBo;
import com.cskaoyan.model.bo.wxcart.CartCheckoutIdBo;
import com.cskaoyan.model.bo.wxcart.CartUpdateBo;
import com.cskaoyan.model.vo.wxcart.WxCartTotal;
import com.cskaoyan.model.vo.wxcart.WxCartTotalListVo;
import com.cskaoyan.model.vo.wxcart.WxCheckoutTotalVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @program: project-market
 * @description:
 * @author: Weiwei Liu
 * @create: 2021-12-02 15:36
 **/
@Service
public class WxCartServiceImpl implements WxCartService {

    @Autowired
    MallCartMapper mallCartMapper;
    @Autowired
    MallGoodsMapper goodsMapper;
    @Autowired
    MallGoodsProductMapper goodsProductMapper;
    @Autowired
    MallUserMapper userMapper;
    @Autowired
    MallAddressMapper addressMapper;
    @Autowired
    MallCouponMapper couponMapper;
    @Autowired
    MallCouponUserMapper couponUserMapper;
    @Autowired
    MallOrderMapper orderMapper;

    @Override
    public WxCartTotalListVo list(Integer userId) {


        MallCartExample example = new MallCartExample();

        example.createCriteria().andUserIdEqualTo(userId).andDeletedEqualTo(false);

        List<MallCart> carts = mallCartMapper.selectByExample(example);

        WxCartTotal cartTotal = new WxCartTotal();

        Integer goodsCount = 0;
        Integer checkedGoodsCount = 0;
        BigDecimal goodsAmount = new BigDecimal(0);
        BigDecimal checkedGoodsAmount = new BigDecimal(0);

        for (MallCart cart : carts) {
            goodsCount = goodsCount + cart.getNumber();
            goodsAmount = goodsAmount.add(cart.getPrice().multiply(new BigDecimal(cart.getNumber())));
            if (cart.getChecked()) {
                checkedGoodsCount = cart.getNumber() + checkedGoodsCount;
                checkedGoodsAmount = checkedGoodsAmount.add(cart.getPrice().multiply(new BigDecimal(cart.getNumber())));
            }
        }
        cartTotal.setGoodsCount(goodsCount);
        cartTotal.setCheckedGoodsCount(checkedGoodsCount);
        cartTotal.setCheckedGoodsAmount(checkedGoodsAmount);
        cartTotal.setGoodsAmount(goodsAmount);

        WxCartTotalListVo vo = new WxCartTotalListVo();
        vo.setCartTotal(cartTotal);
        vo.setCartList(carts);

        return vo;
    }

    @Override
    public WxCartTotalListVo checked(CartCheckedBo bo, Integer userId) {

        // 按照商品id批量修改
        List<Integer> productIds = bo.getProductIds();
        boolean isChecked = bo.getIsChecked() != 0;

        for (Integer productId : productIds) {

            mallCartMapper.updateCheckedByUserIdAndProductId(productId, isChecked, userId);

        }

        return list(userId);

    }

    @Override
    public Integer update(CartUpdateBo bo, Integer userId) {

        Integer i = mallCartMapper.updateCartMsgById(bo, userId);

        if (i == 1) return 0;

        return 10000;
    }

    @Override
    public Integer delete(List productIds, Integer userId) {

        for (Object productId : productIds) {
            mallCartMapper.deleteCartByProductId((Integer) productId, userId);
        }
        return 0;
    }

    @Override
    public Integer add(CartAddBo bo, Integer userId) {

        MallCart mallCart = new MallCart();

        // 通过goodsId
        int goodsId = bo.getGoodsId();

        // 通过查goods表找到信息
        MallGoodsExample goodsExample = new MallGoodsExample();
        goodsExample.createCriteria().andIdEqualTo(goodsId);
        List<MallGoods> mallGoods = goodsMapper.selectByExample(goodsExample);
        MallGoods goods = mallGoods.get(0);


        // 通过查product表找到规格
        MallGoodsProductExample goodsProductExample = new MallGoodsProductExample();
        goodsProductExample.createCriteria().andIdEqualTo(bo.getProductId());
        List<MallGoodsProduct> mallGoodsProducts = goodsProductMapper.selectByExample(goodsProductExample);
        MallGoodsProduct mallGoodsProduct = mallGoodsProducts.get(0);
        String[] specifications = mallGoodsProduct.getSpecifications();

        // 赋值
        mallCart.setGoodsId(goodsId);
        mallCart.setUserId(userId);
        mallCart.setNumber((short) bo.getNumber());
        mallCart.setChecked(false);
        mallCart.setDeleted(false);
        mallCart.setAddTime(new Date());
        mallCart.setUpdateTime(new Date());
        mallCart.setProductId(bo.getProductId());
        mallCart.setGoodsName(goods.getName());
        mallCart.setGoodsSn(goods.getGoodsSn());
        mallCart.setPrice(goods.getRetailPrice());
        mallCart.setPicUrl(goods.getPicUrl());
        mallCart.setSpecifications(specifications);

        // 先按照规格和goodsId,userId,deleted查询cart是否存在，如果存在，自增，否则新建
        int status = 0;
        MallCartExample cartExample = new MallCartExample();
        cartExample.createCriteria().andUserIdEqualTo(userId).andProductIdEqualTo(bo.getProductId()).andGoodsIdEqualTo(bo.getGoodsId()).andDeletedEqualTo(false);
        List<MallCart> carts = mallCartMapper.selectByExample(cartExample);
        if (carts == null || carts.size() == 0) {
            mallCartMapper.insert(mallCart);

        } else {
            MallCart oldMallCart = carts.get(0);
            oldMallCart.setUpdateTime(new Date());
            oldMallCart.setNumber((short) (oldMallCart.getNumber() + bo.getNumber()));
            mallCartMapper.updateByPrimaryKey(oldMallCart);
        }

        // 查询该用户目前在购物车的所有数据
        cartExample.clear();
        cartExample.createCriteria().andUserIdEqualTo(userId).andDeletedEqualTo(false);
        List<MallCart> newCarts = mallCartMapper.selectByExample(cartExample);

        int count = 0;
        for (MallCart newCart : newCarts) {
            count += newCart.getNumber();
        }

        // 返回购物车中所有商品的number
        return count;

    }

    @Override
    public WxCheckoutTotalVo checkout(CartCheckoutIdBo bo, Integer uid) {


        // 根据uid获取用户信息
        MallUser mallUser = userMapper.selectByPrimaryKey(uid);

        // 根据addressId获取用户地址
//        MallAddressExample addressExample = new MallAddressExample();
//        addressExample.createCriteria().andUserIdEqualTo(uid);
//        List<MallAddress> mallAddresses = addressMapper.selectByExample(addressExample);
//        MallAddress mallAddress = mallAddresses.get(0);
        MallAddress mallAddress = addressMapper.selectByPrimaryKey(bo.getAddressId());


        // 根据uid获取购物车信息
        MallCartExample cartExample = new MallCartExample();
        cartExample.createCriteria().andUserIdEqualTo(uid).andDeletedEqualTo(false);
        List<MallCart> carts = mallCartMapper.selectByExample(cartExample);

        ArrayList<MallCart> checkedGoodsList = new ArrayList<>();

        BigDecimal goodsTotalPrice = new BigDecimal(0);

        for (MallCart cart : carts) {
            if (cart.getChecked()) {
                // 购物车里所有选中的商品和总价信息
                checkedGoodsList.add(cart);

                BigDecimal multiply = cart.getPrice().multiply(new BigDecimal(cart.getNumber()));

                goodsTotalPrice = goodsTotalPrice.add(multiply);
            }
        }

        // 获取CouponUser信息
        MallCouponUserExample couponUserExample = new MallCouponUserExample();
        couponUserExample.createCriteria().andUserIdEqualTo(uid).andDeletedEqualTo(false);

        Integer availableCouponLength = 0;

        List<MallCouponUser> couponUsers = couponUserMapper.selectByExample(couponUserExample);
        for (MallCouponUser couponUser : couponUsers) {
            if (couponUser.getStatus() == 0) {
                availableCouponLength++;
            }
        }


        BigDecimal couponPrice = new BigDecimal("0");
        Integer couponId = bo.getCouponId();

        MallCouponExample couponExample = new MallCouponExample();

        // -1代表不选，0代表全选
        if (couponId == 0) {
            List<MallCoupon> mallCoupons = couponMapper.selectByExample(couponExample);
            if (mallCoupons != null || mallCoupons.get(0) != null) {
                MallCoupon mallCoupon = mallCoupons.get(0);
                couponId = mallCoupon.getId();
            }
        } else if (couponId > 0) {
            MallCoupon mallCoupon = couponMapper.selectByPrimaryKey(couponId);
            couponPrice = mallCoupon.getDiscount();
        } else {
            couponId = -1;
        }


        // 其他部分
        BigDecimal actualPrice = new BigDecimal(0);  // 实付款=商品总价+运费-优惠价格
        BigDecimal grouponPrice = new BigDecimal(0);  // 团购价格
        BigDecimal orderTotalPrice = new BigDecimal(0);  // 商品总价
        BigDecimal freightPrice = new BigDecimal(0);  // 运费


        MallOrderExample orderExample = new MallOrderExample();
        orderExample.createCriteria().andUserIdEqualTo(uid);
        List<MallOrder> mallOrders = orderMapper.selectByExample(orderExample);

        if (mallOrders != null && mallOrders.get(0) != null) {
            MallOrder mallOrder = mallOrders.get(0);
            grouponPrice = mallOrder.getGrouponPrice();
            freightPrice = mallOrder.getFreightPrice();
            orderTotalPrice = goodsTotalPrice;
        }

        actualPrice = actualPrice.add(orderTotalPrice).add(freightPrice).subtract(couponPrice);

        if (actualPrice.compareTo(new BigDecimal(0)) < 0) actualPrice = new BigDecimal(0);

        // 赋值
        WxCheckoutTotalVo vo = new WxCheckoutTotalVo();

        vo.setActualPrice(actualPrice);  //
        vo.setOrderTotalPrice(orderTotalPrice);  //
        vo.setCartId(bo.getCartId());  // 4
        vo.setUserCouponId(bo.getUserCouponId()); // 5
        vo.setCouponId(couponId); // 5.5
        vo.setGoodsTotalPrice(goodsTotalPrice); // 6
        vo.setAddressId(mallAddress.getId());  //7
        vo.setGrouponPrice(grouponPrice); //
        vo.setCheckedAddress(mallAddress);   // 9
        vo.setCouponPrice(couponPrice);  // 10
        vo.setAvailableCouponLength(availableCouponLength);  // 11
        vo.setFreightPrice(freightPrice);  //
        vo.setCheckedGoodsList(checkedGoodsList); // 13


        return vo;
    }

    @Override
    public Integer fastadd(CartAddBo bo, Integer userId) {

        MallCart mallCart = new MallCart();

        // 通过goodsId
        int goodsId = bo.getGoodsId();

        // 通过查goods表找到信息
        MallGoodsExample goodsExample = new MallGoodsExample();
        goodsExample.createCriteria().andIdEqualTo(goodsId);
        List<MallGoods> mallGoods = goodsMapper.selectByExample(goodsExample);
        MallGoods goods = mallGoods.get(0);

        // 通过查product表找到规格
        MallGoodsProductExample goodsProductExample = new MallGoodsProductExample();
        goodsProductExample.createCriteria().andIdEqualTo(bo.getProductId());
        List<MallGoodsProduct> mallGoodsProducts = goodsProductMapper.selectByExample(goodsProductExample);
        MallGoodsProduct mallGoodsProduct = mallGoodsProducts.get(0);
        String[] specifications = mallGoodsProduct.getSpecifications();

        // 赋值
        mallCart.setGoodsId(goodsId);
        mallCart.setUserId(userId);
        mallCart.setNumber((short) bo.getNumber());
        mallCart.setChecked(false);
        mallCart.setDeleted(false);
        mallCart.setAddTime(new Date());
        mallCart.setUpdateTime(new Date());
        mallCart.setProductId(bo.getProductId());
        mallCart.setGoodsName(goods.getName());
        mallCart.setGoodsSn(goods.getGoodsSn());
        mallCart.setPrice(goods.getRetailPrice());
        mallCart.setPicUrl(goods.getPicUrl());
        mallCart.setSpecifications(specifications);

        // 直接插入数据库中，返回cartId
        mallCartMapper.insert(mallCart);

        // 返回购物车中所有商品的number
        return mallCart.getId();

    }
}
